<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮 -->
      <template #toolbar>
        <div v-for="(item, index) in butData" :key="index">
          <a-button :key="index" :type="item.color" @click="item.do" v-auth="item.auth">
            <Icon :icon="item.icon" /> {{ t(item.title) }}
          </a-button>
        </div>
      </template>
      <!-- 表格插槽 -->
      <template #prtqtyColumn="{ record }">
        <!-- input 输入框 -->
        <a-input v-model:value="record.prtqty" :min="1" :max="10" :step="1" />
      </template>
      <!-- 勾选 -->
      <template #checkBox="{ record, column }">
        <a-checkbox :checked="record[column.dataIndex] == '1' ? true : false" />
      </template>
    </BasicTable>
    <!-- <InputForm @register="registerDrawer" @success="handleSuccess" /> -->
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      title="产品码补打"
      @ok="handleModal"
      :width="1000"

    >
      <BasicTable @register="registerPuArrTable" @row-click="handlePuArrRowClick" />
    </BasicModal>
    <BasicModal
      v-bind="$attrs"
      @register="registerModal"
      title="标签打印"
      @ok="handleModalInvClick"
      :width="500"
      :height="300"
      okText="下载文件"
      cancelText="全部关闭"
    > 
       <div class="flex" style="justify-content: center;align-items: center;height: 100px;font-weight: bold;font-size: 20px;">
        {{ fileName }}
       </div>
      <!-- <BasicTable @register="registerPuArrTable" @row-click="handlePuArrRowClick" /> -->
    </BasicModal>
    <PrintModal @register="registerPrintModal" />
    <FormImport @register="registerImportModal" @success="handleSuccessFormImport" />
    <barSizeTypeForm @register="registerBarSizeTypeModal" />
  </div> 
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsWmsBarcodePrintListInv',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, watch, ref, onMounted } from 'vue';
  
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, useTable } from '/@/components/Table';
  import { basInvDelete, updateFbStatus, savePic } from '/@/api/bas/inv/basInv';
  import { printSnNumber } from '/@/api/wms/barcode/encode';
  import { listSet, customListData } from '/@/api/test/testData';
  import { tabConfigData, schemasData } from '/@/utils/custom';
  import { useDrawer } from '/@/components/Drawer';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  //import InputForm from './form.vue';
  import PrintModal from '/@/components/print/printModal.vue';
  import FormImport from './formImport.vue';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useGlobSetting } from '/@/hooks/setting';
  import barSizeTypeForm from './barSizeTypeForm.vue';
  import { BarTypeEnum } from '/@/enums/defEnum';
  const { ctxPath } = useGlobSetting();
  

  const props = defineProps({
    treeCode: String,
    treeName: String,
  });

  const { t } = useI18n('bas.inv.basInv');
  const { showMessage } = useMessage();

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    showAdvancedButton: true,
    schemas: [],
  });

  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });
  let title = ref('');
  let cinvcode = ref('');
  const fileName = ref('');
  const pdfUrl = ref('');

  const actionColumn: BasicColumn = {
    width: 120, //操作按钮宽度
    actions: (record: Recordable) => [
      {
        icon: 'clarity:timeline-line',
        title: t('详情配置'),
        onClick: handleDetails.bind(this, { cinvcode: record.cinvcode }),
        // auth: 'test:testData:edit',
      },
    ],
  };

  const tableColumnsPrint: BasicColumn[] = [
    {
      title: t('存货编码'),
      dataIndex: 'cinvcode',
      key: 'a.cinvcode',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('存货名称'),
      dataIndex: 'cinvname',
      key: 'a.cinvname',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('批次'),
      dataIndex: 'cbatch',
      key: 'a.cbatch',
      sorter: true,
      width: 100,
      align: 'center',
      editable: true,
      edit: true,
      editRow: true,
      editComponent: 'Input',
      editComponentProps: {
        maxlength: 50,
      },
      editRule: true,
    },
  ];

  const [registerPuArrTable, invPrintTable] = useTable({
    columns: tableColumnsPrint,
    rowKey: 'id',
    pagination: false,
    bordered: true,
    
  });

  const [registerTable, { reload, setProps, getForm, getSelectRows }] = useTable({
    //actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
    
  });

  const [registerModal, { openModal, closeModal }] = useModal();
  const [registerImportModal, { openModal: importModal }] = useModal();
  const [registerBarSizeTypeModal, { openModal: openBarSizeTypeModal }] = useModal();

  onMounted(async () => {
    const res = await listSet({ viewCode: 'bas_inv_print_list' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

    console.log('layVoucherView', layVoucherView.value);

    // 给表格里面的每一行的prtqty 值赋默认值为1
    tableColumns.value.forEach((item) => {

      if (item.dataIndex == 'prtqty') {
        // item.customRender = (record) => {
        //   // 为input框赋值
        //   return record.prtqty ? Number(record.prtqty) : 1;
        // };
      }
    });
    butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    butData.value.forEach((item) => {
      console.log('item.btnKey', item.btnKey);
      if (item.btnKey == 'btnPrintInv') {
        item.do = () => handlePrintInv({});
      }
      if(item.btnKey == 'btnPackImport'){
        item.do = () => handleImportPrint({});
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      ...listTabConfig.value,
      api: customListData,
      beforeFetch: (params) => {
        for (const key in params) {
          if (Array.isArray(params[key])) {
            params[key + '_gte'] = params[key][0];
            params[key + '_lte'] = params[key][1];
            delete params[key];
          }
        }
        console.log('params', params);
        params.url = listTabConfig.value.api;
        return params;
      },
      afterFetch: (params) => {
        console.log('params==afterFetch', params);
        // 给一行数据的prtqty 值赋默认值为1
        params.forEach((item) => {
          item.prtqty = 1;
        });
        return params;
      },
    });

    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerPrintModal, { openModal: openPrintModal }] = useModal();

  watch(
    () => props.treeCode,
    async () => {
      await getForm().setFieldsValue({
        clsCode: props.treeCode,
        'basInv.invCls.treeName': props.treeName,
      });
      reload();
    },
  );

  function handleDetails(record: Recordable) {
    cinvcode.value = record.cinvcode;
    // cversion.value = record.cversion;
    // title.value = `首页配置 （版本号：${record.cversion}）`;
    openAppsetDetailsDrawer(true);
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  function handlePuArrRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  async function handleDelete(record: Recordable) {
    const res = await basInvDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  // 补打：批次
  async function handlePrint() {
    let arr = await getSelectRows();
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    }
    await openModal(true, {});
    invPrintTable.setTableData(arr);
  }

  // 产品码补打

  // 产品码打印
  async function handlePrintInv() {
    let arr = await getSelectRows();
    if (getSelectRows().length == 0) {
      showMessage(t('请先选择一行数据'));
      return;
    }
    openBarSizeTypeModal(true, { arr: arr, barSizeType: BarTypeEnum.Inventory });
    // const idsArr = arr.map((item) => {
    //   return item.id;
    // });
    // const prtqty = arr.map((item) => {
    //   return item.prtqty;
    // });
    // let params = {
    //   selIds: idsArr.join(','),
    //   barType: invBarType,
    //   barSizeType: getForm().getFieldsValue().barSizeType,
    //   prtQtys: prtqty.join(','),
    // };
    // // 查询条件
    // const res = await printSnNumber(params);
    // if(res.result == "true"){
    //   fileName.value = res.fileName;
    //   pdfUrl.value = res.pdfUrl;
    //   await openModal(true, res);
    // } else {
    //   showMessage(res.message);
    // }
    // openPrintModal(true, params);
    
  }

  // 标件产品打印

  function handleSuccess() {
    reload();
  }

  function handleModalInvClick(record: Recordable) {
    // 下载
    // pdfUrl
    downloadByUrl({ url: ctxPath + pdfUrl.value });
    closeModal();
  }
  function handleImportPrint() {
    importModal(true, {});
  }
  async function handleSuccessFormImport(data) {
    console.log(data);
    if(data.result  == 'true'){
      fileName.value = data.fileName;
      pdfUrl.value = data.pdfUrl;
      await openModal(true, data);
    } else {
      showMessage(data.message);
    }
  }
</script>
<style scoped>
:deep(.jeesite-editable-cell__action) {
  display: none;
}

/* .jeesite-editable-cell__action {
    display: none;
  } */

:deep(.edit-cell-align-center) {
  width: 100% !important;
}
</style>
